// pages/chat/chat.js
const commonUser = require('../../common/commonUser.js');
const customRequst = require('../../common/customRequst');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //接受消息人基本信息
    youInfo: {},
    //发送人信息
    meInfo: {},
    //加载页数
    page: 1,
    //聊天记录
    chatList: [],
    //聊天控制类
    chat: {},
    inputValue: '',
    scroll_height: 0,
    isShowTop: false,
    isShowModelUp: false, //底部弹框显示true,隐藏为false 
    peris_id: 0,
    rightMenuObj: {
      isShow: true,
      top: 0,
      right: 0,
      record_id: '',
    },
    isShowPrice: false,
    periPrice: '',
    session_id: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    let peris_id = options.peris_id;
    if (peris_id != undefined && peris_id != null && peris_id != '') {
      that.setData({
        peris_id: peris_id
      })
    } else {}

    let scrollHeight = app.scrollHeight(that);
    that.setData({
      scroll_height: scrollHeight
    });

    app.globalData.Chat.windowsobj = this;
    if (!app.globalData.Chat.serviceConfig.isWebScoket) {
      let userIsLogin = customUser.getUserToken();
      if (userIsLogin) {
        app.globalData.Chat.init();
      }
    }
    app.globalData.Chat.chat_window = true;
    that.data.chat = app.globalData.Chat;
    that.data.meInfo = commonUser.getUserInfo();

    let navigationBarTitleText = '信息咨询'
    switch (that.data.peris_id) {
      case "0":
        navigationBarTitleText = '编辑咨询';
        wx.setNavigationBarTitle({
          title: navigationBarTitleText,
        })
        break;
      case "-1":
        navigationBarTitleText = '论著出书咨询';
        wx.setNavigationBarTitle({
          title: navigationBarTitleText,
        })
        break;
      case "-2":
        navigationBarTitleText = '专利申请咨询';
        wx.setNavigationBarTitle({
          title: navigationBarTitleText,
        })
        break;
      case "-3":
        navigationBarTitleText = '软件著作咨询';
        wx.setNavigationBarTitle({
          title: navigationBarTitleText,
        })
        break;
      default:
        //获取书刊信息
        customRequst.postRequest('apiperis/getchatperi', {
          id: that.data.peris_id,
          types: 'chat'
        }).then(function (re) {
          if (re.code == 1) {
            wx.setNavigationBarTitle({
              title: re.data.peri_name
            });
            if (re.data.types_id == 1) {
              that.setData({
                periPrice: re.data.author_reference_price,
                isShowPrice: true
              })
              setTimeout(that.clearPrice, 8000);
            }
          }
        });
        break;
    }

    //获取客服人员
    customRequst.postRequest('api/user/getcustomerid', {}).then(function (re) {
      if (re.code == 1) {
        //创建聊天对象
        let load_message = {
          c: "Message",
          a: "add_session",
          data: {
            user_id: re.data.id + "||admin",
            peri_id: that.data.peris_id
          }
        };
        that.data.chat.sendMessage(load_message);
      } else {
        wx.showToast({
          title: '加载聊天会话失败！',
        })
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
  },

  //清理显示价格
  clearPrice: function () {
    let that = this;
    that.setData({
      periPrice: '',
      isShowPrice: false
    })
  },
  //处理聊天返回数据
  handleChatMag: function (msg) {
    let that = this;
    switch (msg.msgtype) {
      case 'config': //初始化连接完成
        break;
      case 'add_session': //添加聊天对象--返回
        if (msg.code == 1) {
          //初始化聊天对象基本信息
          that.setData({
            youInfo: msg.data
          });
          //加载聊天记录
          let load_message = {
            c: 'Message',
            a: 'chat_record',
            data: {
              session_id: msg.data.id,
              page: 1
            }
          };
          that.data.chat.sendMessage(load_message);
          that.setData({
            session_id: msg.data.id
          })
        } else {
          wx.wx.showToast({
            title: msg.message,
          })
        }
        break;
      case 'chat_record': //返回聊天记录
        if (msg.code == 0) {
          return;
        }
        if (msg.data.page == 1) {
          //清除对话内
        }
        //加载页数
        that.setData({
          page: msg.data.next_page
        });
        //循环添加聊天数据
        let chat_record = msg.data.chat_record;
        //判断是否加载完聊天记录
        if (chat_record[0].data.length <= 0) {
          let data = {
            strtype: "time",
            time: '已加载全部数据'
          }
          that.data.chatList.unshift(data);
          that.setData({
            page: 'done',
            chatList: that.data.chatList
          });
          return;
        }
        for (let i in chat_record) {
          if (msg.data.page == 1) {
            that.buildSessionTime(chat_record[i].datetime, msg.data.page);
          }
          for (let y in chat_record[i].data) {
            that.buildRecord(chat_record[i].data[y], msg.data.page)
          }
          if (msg.data.page != 1) {
            that.buildSessionTime(chat_record[i].datetime, msg.data.page);
          }
        }
        break;
      case 'new_message': //收到新消息
        if (msg.data.id != that.data.session_id) {
          return;
        }
        that.buildRecord(msg.data, 1);
        //标记消息已读
        let load_message = {
          c: 'Message',
          a: 'read_message',
          data: {
            record_id: msg.data.record_id
          }
        };
        that.data.chat.sendMessage(load_message);
        break;
      case 'send_message': //绑定新消息id
        if (msg.code == 1) {
          let id = msg.data.record_id;
          let uuid = msg.data.uuid;
          let msgList = that.data.chatList;
          for (let i in msgList) {
            if (msgList[i]['uuid']) {
              if (uuid == msgList[i]['uuid']) {
                msgList[i]['record_id'] = id;
                break;
              }
            }
          }
          that.setData({
            chatList: msgList
          })
        }
        break;
    }
  },
  //绑定聊天界面数据展示
  buildRecord: function (msg, page) {
    let that = this;
    //处理消息
    let result = that.decodeStr(msg.message);
    //头像
    let avatar;
    if (msg.sender == 'me') {
      avatar = that.data.meInfo.avatar;
    } else {
      avatar = that.data.youInfo.avatar;
    }
    let uuid = 0;
    if (msg.uuid) {
      uuid = msg.uuid;
    }
    let recordData = {
      is_admin: msg.sender,
      strtype: result.type,
      text: result.text,
      avatar: avatar,
      uuid: uuid,
      record_id: msg.id,
    };

    let chatList = that.data.chatList;

    if (page == 1) {
      chatList.push(recordData);
    } else {
      chatList.unshift(recordData);
    }
    that.setData({
      chatList: chatList
    });
    if (page == 1) {
      that.pageScrollToBottom();
    } else {
      that.pageScrollTop();
    }

  },
  //置底
  pageScrollToBottom: function () {
    let that = this;
    var query = wx.createSelectorQuery();
    query.select('#msg_list').boundingClientRect()
    query.exec(function (res) {
      that.setData({
        scroll_height: res[0].height,
      })
    })
  },
  //置顶
  pageScrollTop: function () {
    let that = this;
    that.setData({
      scroll_height: 10,
    })
  },
  //绑定时间
  buildSessionTime: function (data, page) {
    let that = this;
    //插入顶部时间
    data = {
      strtype: "time",
      time: data
    }
    let chatList = that.data.chatList;
    if (page == 1) {
      chatList.push(data);
      that.setData({
        chatList: chatList
      })
    } else {
      //插入对话尾部时间
      //that.data.chatList.unshift(data);
      // that.setData({
      //  chatList: that.data.chatList
      //})
    }
  },
  //点击发送消息
  onSendMsg(e) {
    let that = this;
    let msg = e.detail.value;
    let uuid = that.createUuid();
    let load_message = {
      c: 'Message',
      a: 'send_message',
      data: {
        message: msg,
        session_id: that.data.youInfo.id,
        uuid: uuid
      }
    };
    that.data.chat.sendMessage(load_message);
    //将消息填充到对话中
    let recordData = {
      sender: 'me',
      message: msg,
      uuid: uuid
    };
    that.setData({
      inputValue: ''
    });
    that.buildRecord(recordData, 1);

  },
  //生产聊天uuid
  createUuid: function () {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";
    let uuid = s.join("");
    return uuid;
  },
  //打开底部弹框
  showModelUp: function () {
    var that = this;
    if (that.data.isShowModelUp == false) {
      that.setData({
        isShowModelUp: true,
      })
    } else {
      that.setData({
        isShowModelUp: false,
      })
    }
  },
  //关闭底部弹框
  closeModelUp: function () {
    var that = this;
    that.setData({
      isShowModelUp: false,
    })
  },
  //选择照片
  chooseImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths[0];
        let filename;
        wx.uploadFile({
          url: app.globalData.workAipDomain + 'api/common/upload_file',
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            user: 'test'
          },
          success(res) {
            res = JSON.parse(res.data);
            filename = res.data.url;
            let msg = that.buildChatImg(filename);
            let uuid = that.createUuid();
            let load_message = {
              c: 'Message',
              a: 'send_message',
              data: {
                message: msg,
                session_id: that.data.youInfo.id,
                uuid: uuid
              }
            };
            that.data.chat.sendMessage(load_message);
            let recordData = {
              sender: 'me',
              message: msg,
              uuid: uuid
            };
            that.buildRecord(recordData, 1);
          },
          fail: function (re) {
            console.log(re);
          }
        });
        //关闭弹窗
        that.closeModelUp();
      }
    })
  },
  //拍摄
  paishe: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        let filename;
        wx.uploadFile({
          url: app.globalData.workAipDomain + 'api/common/upload_file',
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            user: 'test'
          },
          success(res) {
            res = JSON.parse(res.data);
            filename = res.data.url;
            let msg = that.buildChatImg(filename);
            let uuid = that.createUuid();
            let load_message = {
              c: 'Message',
              a: 'send_message',
              data: {
                message: msg,
                session_id: that.data.youInfo.id,
                uuid: uuid
              }
            };
            that.data.chat.sendMessage(load_message);
            //将消息填充到对话中
            let recordData = {
              sender: 'me',
              message: msg,
              uuid: uuid
            };
            that.buildRecord(recordData, 1);
          },
          fail: function (re) {
            console.log(re);
          }
        });
        //关闭弹窗
        that.closeModelUp();
      }
    })
  },
  //绑定文件下载
  buildChatA: function (filepath, file_suffix) {
    return '<a href="' + filepath + '" download="">点击下载：' + file_suffix + ' 文件</a>';
  },
  //绑定聊天图片
  buildChatImg: function (filename) {
    return '<img class="msg_image" title="图片" src="' + filename + '" />';
  },
  //解析字符串
  decodeStr: function (str) {
    let that = this;
    let reData = {
      type: "",
      text: "",
    }
    if (str.indexOf('<a href="') >= 0) {
      reData.type = 'href';
      //获取字符串中的路径
      let reg = /href=[\'\"]?([^\'\"]*)[\'\"]?/i;
      let aryStr = str.match(reg);
      if (aryStr) {
        let src = aryStr[1];
        if (src) {
          if (src.indexOf(that.data.chat.config.filepath) < 0) {
            src = that.data.chat.config.filepath + src;
          }
          reData.text = src;
        }
      }
    } else if (str.indexOf('<img') >= 0) {
      reData.type = 'img';
      //获取图片
      let reg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
      let aryStr = str.match(reg);
      if (aryStr) {
        let src = aryStr[1];
        if (src == undefined || src == '') {
          src = '';
        }
        if (src) {
          if (src.indexOf(that.data.chat.config.filepath) < 0) {
            src = that.data.chat.config.filepath + src;
          }
          reData.text = src;
        }
      }
    } else {
      reData.type = 'string';
      reData.text = str;
    }
    return reData;
  },
  //图片预览
  imgYu: function (event) {
    var src = event.currentTarget.dataset.src;
    let urls = [src];
    wx.previewImage({
      current: src,
      urls: urls
    })
  },
  //实时记录发送消息数据
  setMsgData: function (e) {
    let that = this;
    let msgData = e.detail.value;
    that.setData({
      inputValue: msgData
    });
  },
  //绑定发送按钮
  bindSendBtn: function () {
    let that = this;
    let msg = that.data.inputValue
    let uuid = that.createUuid();
    let load_message = {
      c: 'Message',
      a: 'send_message',
      data: {
        message: msg,
        session_id: that.data.youInfo.id,
        uuid: uuid
      }
    };
    that.data.chat.sendMessage(load_message);
    //将消息填充到对话中
    let recordData = {
      sender: 'me',
      message: msg,
      uuid: uuid
    };
    that.setData({
      inputValue: ''
    });
    that.buildRecord(recordData, 1);
  },
  //长按触发右键菜单事件
  touchMsgEnd: function (e) {},
  //加载上一页消息
  getOldMsgList: function (e) {
    let that = this;
    if (that.data.page != 'done') {
      if (e.currentTarget.offsetTop == 0) {
        //加载聊天记录
        let load_message = {
          c: 'Message',
          a: 'chat_record',
          data: {
            session_id: that.data.session_id,
            page: that.data.page
          }
        };
        that.data.chat.sendMessage(load_message);
      }
    }
  }
})